import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import PropTypes from 'prop-types';
import { injectIntl } from 'react-intl';

import _ from 'lodash';
import {
  AccordionSet,
  Accordion,
  Checkbox,
  Button,
  Col,
  Badge,
  Row
} from '@folio/stripes/components';
import ActivitySearchList from './fruit-list';
import ActivityUserList from './guest-list';
import UserList from './wait-meal-list';
import ActDataSachet from './cake-fruit';

class CakeHub extends Component {
    static propTypes = {
      handleSubmit: PropTypes.func.isRequired,
      actData: PropTypes.shape({
        activityName: PropTypes.string,
        activityDateTime: PropTypes.string,
        quota: PropTypes.string,
        surplus: PropTypes.string
      }).isRequired,
      mutator: PropTypes.shape({
        findHttpInvoke: PropTypes.shape({
          GET: PropTypes.func.isRequired
        }).isRequired
      }).isRequired,
      shippingData: PropTypes.func.isRequired,
      intl: PropTypes.func.isRequired,

      labelName:PropTypes.object,
      cancel:PropTypes.func
    };

    constructor(props) {
      super(props);
      this.state = {
        userdata: [],
        actData: {},
        removeFlag: true,
        commitFlag: true,
        accordions: {
          actMsg: true,
          userMsg: false,
          userListMsg: false
        }
      };
      this.intl = this.props.intl;
      this.label = this.props.labelName;
    }

    render() {
      const { handleSubmit, intl } = this.props;

      return (
        <div style={{ height: '100%', overflow: 'auto' }}>
          <AccordionSet
            accordionStatus={this.state.accordions}
            onToggle={this.onToggleSection}
          >
            <Row style={{ width: '100%' }} center="xs">
              <Col xs={8}>
                <Accordion label={intl.formatMessage({ id: 'ui-party.reserve.add.partyMessage' })} id="actMsg">
                  <ActivitySearchList
                    selectActivityTarget={this.selectActTarget}
                    labelName={this.props.labelName}
                  />
                  {intl.formatMessage({ id: 'ui-party.reserve.add.selectedPartyMessage' })}
                  <hr />
                  <ActDataSachet
                    actData={this.state.actData}
                    resetData={this.resetData}
                    labelName={this.props.labelName}
                  />
                </Accordion>
              </Col>
            </Row>
            <Row style={{ width: '100%' }} center="xs">
              <Col xs={8}>
                <Accordion label={intl.formatMessage({ id: 'ui-party.reserve.add.appointmentReaderList' })} id="userMsg">
                  <ActivityUserList
                    selectActivityUserTarget={this.selectActivityUserTarget}
                    labelName={this.props.labelName}
                  />
                </Accordion>
              </Col>
            </Row>
            <Row style={{ width: '100%' }} center="xs">
              <Col xs={8}>
                <Accordion
                  label={
                    <div>
                      <span>
                        {intl.formatMessage({ id: 'ui-party.reserve.add.partyMessage' })}

                      </span>
                      <Badge color="red" size="small">
                        {this.state.userdata.length}
+
                      </Badge>
                    </div>
                                }
                  id="userListMsg"
                  displayWhenOpen={
                    <Button
                      disabled={this.state.removeFlag}
                      onClick={() => {
                        this.allRemove();
                      }}
                    >
                      {intl.formatMessage({ id: 'ui-party.reset' })}
                    </Button>
                                }
                >
                  <UserList
                    dataList={this.state.userdata}
                    removeUser={this.removeUser}
                    allRemove={this.allRemove}
                    removeFlag={this.state.removeFlag}
                  />
                </Accordion>
              </Col>
            </Row>
          </AccordionSet>
          <Row style={{ width: '100%' }} center="xs">
            <Col xs={8}>
              <form data-test-form-page id="form-search" onSubmit={handleSubmit}>
                <Field
                  component={Checkbox}
                  name="quotaFlag"
                  label={intl.formatMessage({ id: 'ui-party.reserve.add.extraQuota' })}
                  inline
                />
              </form>
            </Col>
          </Row>
          <Row style={{ width: '100%' }} center="xs">
            <Col xs={8}>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  borderTop: '1px solid rgba(0, 0, 0, 0.2)',
                  minHeight: '44px',
                  padding: '15px'
                }}
              >
                <div>
                  <Button buttonStyle="default mega" onClick={() => { this.props.cancel(); }}>
                    {intl.formatMessage({ id: 'ui-party.cancel' })}
                  </Button>
                  <Button
                    buttonStyle="primary mega"
                    type="submit"
                    disabled={this.state.commitFlag}
                    onClick={() => {
                      this.initialValues = {
                        userdata: this.state.userdata,
                        actData: this.state.actData
                      };
                      this.props.handleSubmit();
                    }}
                  >
                    {intl.formatMessage({ id: 'ui-party.saveAndExit' })}
                  </Button>
                </div>
              </div>
            </Col>
          </Row>

        </div>
      );
    }

    /** *
     * 选择一条活动信息
     * @param item
     */
    selectActTarget = item => {
      if (item) {
        let commitFlag = this.checkCommitFlag();
        if (this.state.userdata.length >= 1) {
          commitFlag = false;
        }

        // 查找报名数量
        const { GET } = this.props.mutator.findHttpInvoke;
        const query = `( isDel = 0 and partyId = ${item.id}* )`;
        GET({ params: { query } }).then(response => {
          item.surplus = response.totalRecords;
          this.setState({
            actData: item,
            commitFlag
          });
        });
      }
    };

    /**
     *     选择并添加一个用户
     */
    selectActivityUserTarget = item => {
      const { GET } = this.props.mutator.findHttpInvoke;
      const barcode = item.barcode;
      const _this = this;
      const { intl } = this.props;
      if (item) {
        const query = `(isDel = 0 and partyId = ${this.state.actData.id} and readerReserveGroup == *"barcode"*: *"${barcode}"*)`;
        GET({ params:{ query } }).then((res) => {
          if (res && res.totalRecords !== 0) {
            alert(intl.formatMessage({ id: 'ui-party.reserve.add.verifyMessageUser' }));
          } else {
            const userdata = _this.state.userdata;
            if (userdata.length === 0) {
              userdata.push(item);
            } else {
              for (let i = 0; i < userdata.length; i++) {
                if (userdata[i].barcode === barcode) {
                  return false;
                }
              }
              userdata.push(item);
            }
            const removeFlag = false;
            const commitFlag = this.checkCommitFlag();
            this.setState({
              userdata,
              removeFlag,
              commitFlag
            });
          }
        }).catch(e => {
          console.debug(e);
        });
      }
    };

    resetData = () => {
      const commitFlag = true;
      this.setState({
        actData: {},
        commitFlag
      });
    };

    /**
     * 删除一个已经选择的用户
     * @param item
     */
    removeUser = item => {
      if (item) {
        const userdata = [];
        const oList = this.state.userdata;
        for (let i = 0; i < oList.length; i++) {
          if (oList[i].barcode !== item.barcode) {
            userdata.push(oList[i]);
          }
        }
        let removeFlag = false;
        let commitFlag = this.checkCommitFlag();
        if (userdata.length === 0) {
          removeFlag = true;
          commitFlag = true;
        }

        this.setState({
          userdata,
          removeFlag,
          commitFlag
        });
      }
    };

    /**
     * 删除所有的用户
     */
    allRemove = () => {
      // eslint-disable-next-line no-alert
      // eslint-disable-next-line no-restricted-globals
      const { intl } = this.props;
      if (confirm(intl.formatMessage({ id: 'ui-party.reserve.add.resetUserGroup' }))) {
        const removeFlag = true;
        const userdata = [];
        const commitFlag = true;
        this.setState({
          userdata,
          removeFlag,
          commitFlag
        });
      }
    };

    allRemoveSys = () => {
      const removeFlag = true;
      const userdata = [];
      const commitFlag = true;
      this.setState({
        userdata,
        removeFlag,
        commitFlag
      });
    };

    exitPage = () => {

    };

    checkCommitFlag = () => {
      const commitFlag = true;
      if (
        JSON.stringify(this.state.userdata) === '[]' ||
            JSON.stringify(this.state.actData) === '{}'
      ) {
        return commitFlag;
      } else {
        return !commitFlag;
      }
    };

    componentWillUpdate(nextProps, nextState) {
      nextProps.shippingData(nextState);
    }

    // 侧栏选择
    onToggleSection = ({ id }) => {
      const { intl } = this.props;
      this.setState(curState => {
        const newState = _.cloneDeep(curState); // 克隆一个对象
        const flag = !curState.accordions['' + id + ''];
        newState.accordions['' + id + ''] = flag;

        if (id === 'userMsg' || id === 'userListMsg') {
          if (JSON.stringify(curState.actData) === '{}' && flag) {
            alert(intl.formatMessage({ id: 'ui-party.reserve.add.selectActivityGroup' }));
            return false;
          }
        }
        if (id === 'actMsg') {
          if (JSON.stringify(curState.actData) === '{}' && flag) {
            newState.accordions['' + id + ''] = flag;
            return newState;
          }
        }
        if (flag) {
          const accordionsKey = Object.keys(newState.accordions);
          accordionsKey.map(k => {
            if (k !== id) {
              newState.accordions['' + k + ''] = true;
            }
          });
        }
        return newState;
      });
    };
}

export default injectIntl(
  reduxForm({
    form: 'AddAppointmentFrom',
    navigationCheck: true,
    enableReinitialize: true
  })(CakeHub)
);
